package cn.agiledata.bank.barcodepayment.logic;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import cn.agiledata.bank.barcodepayment.exception.BarCodePayException;
import cn.agiledata.bank.common.util.DateUtil;
/**
 * 涓婃捣鑱旈�鍏徃鏀惰垂鏉″舰鐮�
 * 
 * @author 马贤波
 * 
 */
public class CuccBarCode extends AbstractBarCode {
    /**
     * 鏉″舰鐮佸�鐨勯暱搴�
     */
    private static final int CODE_SIZE = 24;

    public BigDecimal getAmount() {
        return getAmount(16, 23);
    }

    public Date getDate() {
        String dateValue = getValue().substring(1,7);
        return DateUtil.string2Date(dateValue, "yyyyMM");
    }
    protected void validate(String barCodeValue) throws BarCodePayException {
        super.validate(barCodeValue);
        if (barCodeValue.length() != CODE_SIZE) {
            throw BarCodePayException.ERROR_BARCODE_LENGTH;
        }
        String b23 = barCodeValue.substring(0,23);
        int e1 = Integer.valueOf(barCodeValue.substring(23,24)).intValue();
        int sum = 0;
        for (int i = 1; i <= b23.length(); i++) {
            sum += intOf(barCodeValue, i);
        }
        String c1 = String.valueOf(sum);
        c1 = c1.substring(c1.length()-1, c1.length());
        int c = Integer.valueOf(c1).intValue();
        if (c != e1){
            throw BarCodePayException.ERROR_BARCODE;
        }
        Date d = getDate();
        Calendar codeDate = Calendar.getInstance();
        codeDate.setTime(d);
        int codeYear = codeDate.get(Calendar.YEAR);
        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        if (codeYear > nowYear && codeYear < nowYear-1) {
            throw BarCodePayException.ERROR_BARCODE;
        }
    }
}
